package com.weizhu.swufer.core.filter;

import com.weizhu.swufer.constant.SwuferConstant;
import com.weizhu.swufer.core.annotation.SwuferFilter;
import com.weizhu.swufer.core.entity.InvokeParam;
import com.weizhu.swufer.core.entity.RpcBaseInfo;
import com.weizhu.swufer.core.rpc.RpcContext;
import com.weizhu.swufer.core.rpc.RpcEngine;
import com.weizhu.swufer.core.exception.RpcException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@SwuferFilter(type = SwuferConstant.FILTER_TYPE_PROVIDER,order = 1)
public class TokenFilter implements Filter{

    private final static Logger logger = LoggerFactory.getLogger(TokenFilter.class);

    @Override
    public Object doFilter(InvokeParam invokeParam, FilterChain filterChain) throws Exception {
        String token = (String) RpcContext.getContext().getParameter(SwuferConstant.TOKEN);
        String interfaceName = invokeParam.getRpcRequest().getInterfaceName();
        RpcBaseInfo rpcBaseInfo = RpcEngine.getInstance().getLocalServiceMap().get(interfaceName);
        String serviceToken = rpcBaseInfo.getToken();
        if (serviceToken != null && !serviceToken.equals(token)){
            logger.info("trace-id:" +invokeParam.getAttachment(SwuferConstant.TRACE_ID)+",invalid token receive:" + token);
            throw new RpcException(RpcException.TOKEN_INVALID,"your token "+ token +" is invalid");
        }
        return filterChain.doFilter(invokeParam);
    }
}
